<?php 
namespace PsiFramework\Classes\Util\Parameters\DAO;

import("Classes.Util.Parameters.Action.ActionMapping");
import("Classes.Util.Parameters.Action.ActionParameters");
import("Classes.Util.Parameters.Action.ActionForward");

use \PsiFramework\Classes\Util\Parameters\Action\ActionMapping;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Util\Parameters\Action\ActionForward;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The ActionMappingDAO class is the class to retrieve action mapping parameters
 *
 * @package Util.Parameters.DAO
 */
class ActionMappingDAO
{

    protected /*DomElement*/ $_actions ;

    public function __construct()
    {
        $this->_actions = null ;
    }

    public function init(\DomElement $actions)
    {
        $this->_actions = $actions ;
    }

    public function initByFile(/*string*/ $file)
    {
        $document = new \DomDocument();
        $document->load($file);
        $this->_actions = $document->documentElement ;
        return $this->_actions->getAttribute("application");
    }

    public function readActionMapping()
    {
        $actionsArray = $this->_actions->getElementsByTagName("action");

        $actionMappings = array();

        foreach ($actionsArray as $action) {
            $actionName = $action->getAttribute("name");
            $actionClass = $action->getAttribute("class");
            $actionTemplate = $action->getAttribute("template");

            $actionParameters = new ActionParameters($actionName, $actionClass);
            if (!isNullOrEmptyString($actionTemplate)) {
                $actionParameters->setTemplate($actionTemplate);
            }

            $forwards = $action->getElementsByTagName("forward");
            foreach ($forwards as $forward) {
                $forwardName = $forward->getAttribute("name");
                $forwardPage = $forward->getAttribute("page");
                $forwardRedirectionAction
                    = $forward->getAttribute("redirectionAction");
                $forwardRedirectToLink
                    = $forward->getAttribute("redirectToLink");

                $actionForward = new ActionForward(
                    $forwardName,
                    $forwardPage,
                    $forwardRedirectionAction,
                    $forwardRedirectToLink
                );
                $actionParameters->addForward($actionForward);
            }

            $actionMappings[$actionParameters->getName()] = $actionParameters ;
        }

        return new ActionMapping($actionMappings);
    }

}
